<template>
    <div>
        <a-modal v-model:open="open" title="上传源码解析分析" @ok="handleOk">
<!--          <input type="file" @change="inputChange"/>-->
          <div v-show="isSelectFile" id="uploader" class="wu-example">
            <!--用来存放文件信息-->
            <div id="thelist" class="uploader-list"></div>
            <div class="btns">
              <div id="picker">选择文件</div>
              <a-progress :percent="percentVal" v-if="percentVal" />
<!--              <div id="number"></div>-->
<!--              <button id="ctlBtn" class="btn btn-default">开始上传</button>-->
            </div>
          </div>

          <div v-show="!isSelectFile">
            <h2>文件上传成功！</h2>

            <h3 style="margin-top: 20px">请选择项目类型</h3>
            <a-radio-group v-model:value="selectType" name="radioGroup">
              <a-radio :value="1">spring-boot</a-radio>
              <a-radio :value="2">spring-cloud</a-radio>
            </a-radio-group>
          </div>
        </a-modal>
    </div>
</template>
<script setup>
import {onMounted, reactive, ref} from "vue";
import {breakpointUpload, uploadCodeFile} from "@/api/file.js";
import sparkMd5 from "spark-md5"
import "@/utils/webuploader.css"
import "@/utils/jquery.js"
import "@/utils/webuploader.js"
import {message} from "ant-design-vue";
const open = ref(false)
const selectType = ref(1)
const isSelectFile = ref(true)
let globalResult = {}
const percentVal = ref(0)
const props = defineProps({
  orderInfo: Object
})
const openModal = () => {
  open.value = true;
  setTimeout(() => {
    if (document.querySelector(".webuploader-pick")) {
      return
    }
    var guid = WebUploader.Base.guid();
    var uploader = WebUploader.create(
        {
          swf: "../js/Uploader.swf",
          server: "/api/breakpoint-upload",
          pick: {
            id: '#picker',
            multiple: false
          },
          auto: true,  // 分块上传设置
          // 是否分块
          chunked: true,
          // 每块文件大小（默认5M）
          chunkSize: 5 * 1024 * 1024,
          // 开启几个并非线程（默认3个）
          threads: 6,
          // 在上传当前文件时，准备好下一个文件
          //        prepareNextFile: true,
          //  sendAsBinary: true,
          //   formData: {"guid": guid},
          //   method: 'POST',
        }
    );

    // 文件上传过程中创建进度条实时显示。
    uploader.on( 'uploadProgress', function( file, percentage ) {
      var $li = $( '#'+file.id ),
          $percent = $li.find('.progress .progress-bar');

      // 避免重复创建
      if ( !$percent.length ) {
        $percent = $('<div class="progress progress-striped active">' +
            '<div class="progress-bar" role="progressbar" style="width: 0%">' +
            '</div>' +
            '</div>').appendTo( $li ).find('.progress-bar');
      }
      console.log($percent)
      $li.find('p.state').text('上传中');

      $percent.css( 'width', percentage * 100 + '%' );
      // $("#number").html((percentage * 100).toFixed(2) + '%')
      const progress = Math.ceil(percentage * 100)
      percentVal.value = progress
      if (progress === 100) {
        console.log(file, "file")
        // $li.find('p.state').text('');
      }
    });
    uploader.on("uploadSuccess", (_, result) => {
      isSelectFile.value = false
      globalResult = result
    })
    // 当有文件被添加进队列的时候
    uploader.on( 'fileQueued', function( file ) {
      // $('#thelist').append( '<div id="' + file.id + '" class="item">' +
      //     '<h4 class="info">' + file.name + '</h4>' +
      //     '<p class="state">等待上传...</p>' +
      //     '</div>' );
    });
    // //上传分块之前设置请求头
    // uploader.on('uploadBeforeSend', function (headers) {
    //     headers={
    //         contentType: "application/json; charset=utf-8",
    //     };
    // });
    //点击上传之前调用的方法
    uploader.on("uploadStart", function (file) {
      // var paramOb = {"guid": guid, "filedId": file.source.ruid}
      // uploader.options.formData.guid = guid;
      // // uploader.options.headers={
      // //    // "Content-Type": "application/json; charset=utf-8",
      // //  //   "Content-Type":"multipart/form-data"
      // // }
      // console.log(uploader.options)

      let time = new Date().valueOf()
      file.name = time + file.name
      // fileArray.push(paramOb);
    });

    // // 文件上传过程中创建进度条实时显示。
    // uploader.on('uploadProgress', function (file, percentage) {
    //     var $li = $('#fileId');
    //     $li.find('p.state').text('上传中（' + parseInt(percentage * 100) + '%）');
    // });
    //文件成功、失败处理
//     uploader.on('uploadSuccess', function (file) {
// //        var successDuid = file.source.ruid;
//       var chunks = file.blocks.length;
//       var realFileName = file.name;
//       var folder = file.id;
//
//       // $.post("/api/file/breakpoint-upload", {
//       //     "guid": guid,
//       //     "chunks": chunks,
//       //     "realFileName": realFileName,
//       //     "folder": folder
//       // }, function (data, status) {
//       //     alert("文件上传成功！")
//       // });
//
//     });

    uploader.on('uploadError', function (file) {
      $('#' + file.id).find('p.state').text('上传出错');
    });
  }, 0)
}
const fileFragment = file => {
  const isLt20M = file.size / 1024 / 1024 <= 20
  const fileList = []
  const fr = new FileReader()
  return new Promise((resolve) => {
    if (isLt20M) {
      fr.readAsArrayBuffer(file)
      fr.addEventListener("load", e=> {
        const spark = new sparkMd5()
        console.log(spark.append)
        spark.append(e.target.result);
        const md5 = spark.end();
        fileList.push({
          file,
          md5,
          id: Math.random(),
          chunks: 1,
          chunk: 1,
          size: file.size,
          name: file.name,
        })
        resolve(fileList)
      })
    } else {
      const id = Math.random()
      fr.readAsArrayBuffer(file)
      fr.addEventListener("load", e=> {
        console.log("文件读取成功")
        const spark = new sparkMd5()
        spark.append(e.target.result);
        const md5 = spark.end();
        console.log("hash计算成功", md5)
        const f = 1024 * 1024 * 20
        let current = 0;
        for (let i = 0; i < file.size; i+= f) {
          let end = Math.min(i + f, file.size); // 确保不会超过文件末尾
          let chunkSize = end - i; // 计算当前分片的实际大小
          fileList.push({
            file: new File([file.slice(i, i + f)], file.name),
            md5,
            id,
            type: "video/mp4",
            lastModifiedDate: "Sun Jul 21 2024 13:35:55 GMT+0800 (中国标准时间)",
            chunks: Math.ceil(file.size / f),
            chunk: current,
            size: chunkSize,
            name: file.name,
          })
          current++;
        }
        console.log(fileList)
        resolve(fileList)
      })
    }
  })
}
const inputChange = async e => {
  const file = e.target.files[0]
  const fileList = await fileFragment(file);
  for (let i = 0; i < fileList.length; i++) {
    const data = await breakpointUpload(fileList[i])
    console.log(data, i)
  }
}

const handleOk = () => {
  const { fileInfo } = globalResult.data
  uploadCodeFile({
    orderNo: props.orderInfo.orderNo,
    fileName: fileInfo.name,
    filePath: fileInfo.path,
    type: selectType.value
  }).then(res => {
    open.value = false
    const { data, code } = res
    isSelectFile.value = true
    percentVal.value = 0
    if (code !== 200) {
      message.error(data.message)
    } else {
      message.success("源码正在分析中，请稍后")
    }
  })
}
defineExpose({
  openModal
})

</script>